package cn.doitedu.javase.io;

import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/2/1
 * @Desc: 学大数据，上多易教育
 *
 *  不断地生成模拟的用户行为数据，写入磁盘文件
 *    {"user_id":1,"event_id":"add_cart","action_time":1706758396000}
 *
 *
 **/
public class _02_FileOutputStream_循环输出示例 {

    public static void main(String[] args) throws Exception {

        String actionLog = "{\"user_id\":${1},\"event_id\":\"${2}\",\"action_time\":${3}}";

        // 上面的数据，生成10000条，写入D:/action_log.txt
        // 要求每条数据中的 ：
        // user_id 是一个随机整数,
        // event_id是这几个之中的随机一个  video_play video_pause ad_show ad_click search page_load  article_share
        // action_time 是生成数据时的真实时间

        String[] events = new String[]{"video_play","video_pause","ad_show","ad_click","search","page_load","article_share"};
        Random random = new Random();


        // 构造一个输出流
        FileOutputStream fileOutputStream = new FileOutputStream("d:/action_log.txt", true);

        for(int i=0;i<10000;i++) {
            String user_id = random.nextInt(1000) + "";
            String event_id = events[random.nextInt(events.length)];
            String action_time = System.currentTimeMillis() + "";

            String replace1 = actionLog.replace("${1}", user_id);
            String replace2 = replace1.replace("${2}", event_id);
            String replace3 = replace2.replace("${3}", action_time);

            // 为我们生成好的json字符串，添加一个换行符
            String data = replace3+"\n";
            fileOutputStream.write(data.getBytes(StandardCharsets.UTF_8));

            Thread.sleep(1000);
        }
    }
}
